package spikes

import (
	"context"
	"fmt"
	"gitee.com/enjoy_5/spikes-rpc/constant"
	pb "gitee.com/enjoy_5/spikes-rpc/proto/spikes" //注意这个路径
	"gitee.com/xuxinzhi2206/corehub/nacos"
	"google.golang.org/grpc"
)

func client(head func(client pb.SpikesServerClient) error) error {
	service, err := nacos.FindHealthService(constant.ServiceName, constant.GroupName)
	if err != nil {
		return fmt.Errorf("服务未发现：：%v", err)
	}
	fmt.Println("发现服务:::", service)
	conn, err := grpc.Dial(service, grpc.WithInsecure())
	if err != nil {
		return fmt.Errorf("连接异常： %s\n", err)
	}
	defer conn.Close()
	// 2. 实例化gRPC客户端
	c := pb.NewSpikesServerClient(conn)
	return head(c)
}

// 创建秒杀活动
func CreateSpikesActivity(in *pb.CreateSpikesActivityRequest) (resp *pb.CreateSpikesActivityResponse, err error) {
	return resp, client(func(client pb.SpikesServerClient) error {
		resp, err = client.CreateSpikesActivity(context.Background(), in)
		if err != nil {
			return err
		}
		return nil
	})
}

// 获取秒杀活动列表
func GetSpikesActivityList(in *pb.GetSpikesActivityListRequest) (resp *pb.GetSpikesActivityListResponse, err error) {
	return resp, client(func(client pb.SpikesServerClient) error {
		resp, err = client.GetSpikesActivityList(context.Background(), in)
		if err != nil {
			return err
		}
		return nil
	})
}

// 获取秒杀商品列表
func GetSpikesGoodsList(in *pb.GetSpikesGoodsListRequest) (resp *pb.GetSpikesGoodsListResponse, err error) {
	return resp, client(func(client pb.SpikesServerClient) error {
		resp, err = client.GetSpikesGoodsList(context.Background(), in)
		if err != nil {
			return err
		}
		return nil
	})
}

// 创建秒杀商品sku关联活动方法
func CreateSpikesGoodsSku(in *pb.CreateSpikesGoodsSkuRequest) (resp *pb.CreateSpikesGoodsSkuResponse, err error) {
	return resp, client(func(client pb.SpikesServerClient) error {
		resp, err = client.CreateSpikesGoodsSku(context.Background(), in)
		if err != nil {
			return err
		}
		return nil
	})
}

// 修改秒杀商品库存
func UpdateSpikesStock(in *pb.UpdateSpikesStockByGoodsIDRequest) (resp *pb.UpdateSpikesStockByGoodsIDResponse, err error) {
	return resp, client(func(client pb.SpikesServerClient) error {
		resp, err = client.UpdateSpikesStock(context.Background(), in)
		if err != nil {
			return err
		}
		return nil
	})
}

// 秒杀商品查询
func GetSpikesGoodsDetail(in *pb.GetSpikesGoodsDetailRequest) (resp *pb.GetSpikesGoodsDetailResponse, err error) {
	return resp, client(func(client pb.SpikesServerClient) error {
		resp, err = client.GetSpikesGoodsDetail(context.Background(), in)
		if err != nil {
			return err
		}
		return nil
	})
}
